package com.fengniao.goods.controller;

import com.fengniao.goods.pojo.Brand;
import com.fengniao.goods.service.BrandService;
import com.github.pagehelper.PageInfo;
import entity.DBOperUtil;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lanhai
 * @date 2021/7/4 18:31
 */
@RestController
@RequestMapping("/brand")
@CrossOrigin // 跨域 当域名、请求端口、协议不一致时就会发生跨域
public class BrandController {

    @Autowired
    private BrandService brandService;

    @GetMapping("/category/{categoryId}")
    public Result<List<Brand>> getBrandByCatId(@PathVariable Integer categoryId) {

        List<Brand> brands = brandService.findBrandByCategoryId(categoryId);
        return Result.data(brands);
    }

    @GetMapping
    public Result<List<Brand>> findAll() {
        List<Brand> all = brandService.findAll();
        return Result.data(all);
    }

    @GetMapping("/{id}")
    public Result<Brand> findById(@PathVariable Integer id) {

        return Result.data(brandService.findById(id));
    }

    @PostMapping
    public Result add(@RequestBody Brand brand) {

        int flag = brandService.add(brand);
        DBOperUtil.checkDBOper(flag, "添加品牌失败");
        return Result.ok("添加品牌成功");
    }

    @PutMapping("/{id}")
    public Result revise(@PathVariable Integer id, @RequestBody Brand brand) {

        brand.setId(id);
        int flag = brandService.revise(brand);
        DBOperUtil.checkDBOper(flag, "添加品牌失败");
        return Result.ok("修改品牌成功");
    }

    @DeleteMapping("/{id}")
    public Result remove(@PathVariable Integer id) {

        int flag = brandService.remove(id);
        DBOperUtil.checkDBOper(flag,"删除品牌失败");
        return Result.ok("删除品牌成功");
    }

    @PostMapping("/search")
    public Result<List<Brand>> findList(@RequestBody Brand brand) {

        List<Brand> list = brandService.findList(brand);
        return Result.data(list);
    }

    @GetMapping("/search/{num}/{size}")
    public Result<PageInfo<Brand>> findPage(@PathVariable("num") Integer num,
                                            @PathVariable("size") Integer size) {

        PageInfo<Brand> page = brandService.findPage(num, size);
        return Result.data(page);
    }

    @PostMapping("/search/{num}/{size}")
    public Result<PageInfo<Brand>> findPage(@RequestBody(required = false) Brand brand,
                                            @PathVariable("num") Integer num,
                                            @PathVariable("size") Integer size) {

        PageInfo<Brand> page = brandService.findPage(brand, num, size);
        return Result.data(page);
    }

}
